﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TELOS_Konverter
{
    class AsxHandler
    {
        private FileOperations fo = new FileOperations();
        private MessageHandler mh = new MessageHandler();
        private StringHandler sth = new StringHandler();
        
        const String CLIP_BEGIN = "clip-begin=\"";
        const String CLIP_END = "clip-end=\"";

        private static double videoStartTime;
        private static double videoEndTime;


        /**getVideoTime
         * Access an smi file and get time (clip-begin="x.x")
         * @param: - fName: file name of the SMI file to be accessed 
         *         - type: either CLIP_BEGIN or CLIP_END
         * @return: time in floating point value
         */
        private void setVideoTime()
        {
            List<string> cache = fo.readFile(fo.getSMIFilePath());
            String newCache = "";
            String searchString = "";
            
            for (int x = 0; x < 2; x++) // This makes the process a bit easier. I didn't want to rewrite the whole method just because it can write START and END
            {
                // First, get the BEGIN of the clip, then the END
                if (x == 0) searchString = CLIP_BEGIN;
                if (x == 1) searchString = CLIP_END;

                for (int i = 0; i < cache.Count; i++)
                {
                    if (sth.isStringInString(cache[i], searchString))
                    {
                        newCache = sth.delete(cache[i], searchString, new List<string> { "before", "include" });
                        if (searchString.Equals(CLIP_BEGIN))
                            newCache = sth.delete(newCache, "\" clip-end", new List<string> { "after", "include" });
                        else if (searchString.Equals(CLIP_END))
                            newCache = sth.delete(newCache, "\" repeat", new List<string> { "after", "include" });

                        // Now save the time to the global vars
                        if (x == 0)
                        {
                            double newStartTime = double.Parse(newCache.Replace(".", ","));
                            if (newStartTime > 1)
                                newStartTime = newStartTime - 1;
                            AsxHandler.videoStartTime = newStartTime;
                        }
                        if (x == 1) AsxHandler.videoEndTime = double.Parse(newCache.Replace(".", ","));

                        break;
                    }
                    else
                    {
                        if (searchString.Equals(CLIP_BEGIN))
                            AsxHandler.videoStartTime = 0;
                        else if (searchString.Equals(CLIP_END))
                            AsxHandler.videoEndTime = 0;
                    }
                }
                FileOperations.asxStartTime = AsxHandler.videoStartTime;
            }
        }

        private double getVideoStartTime() { return AsxHandler.videoStartTime; }
        private double getVideoEndTime() { return AsxHandler.videoEndTime; }

        /**getDuration
         * Access an SMI file and get the duration which equals "end minus begin"
         * @param: file to be accessed
         * @return: duration of the video
         */
        private double getDuration()
        {
            return getVideoEndTime() - getVideoStartTime();
        }

        /**convertMediaFileName
         * @param: Real Media file name
         * @return: the same name but with .wma or .wmv at the end
         */
        private String convertMediaFileName(String rmFileName)
        {
            if (fo.getRMFileType() == FileOperations.RM_FILE_TYPE_AUDIO)
                return rmFileName.Replace(".ra", ".wma").Replace(".rm", ".wma");
            else if (fo.getRMFileType() == FileOperations.RM_FILE_TYPE_VIDEO)
                return rmFileName.Replace(".rv", ".wmv").Replace(".rm", ".wmv");
            else
                return "";
        }

        /**writeASXFile
         * Take the start value and the duration and create a new asx file
         * The file name should be the same as the former SMI file name
         * @param: name of the file that shall be written
         * @return: true if success, else otherwise
         */
        public bool writeASXFile()
        {
            String asxFilePath = fo.getASXFilePath();
            String copyright = fo.getCopyright();
            String mediaFilePath = fo.getServerMediaFilePath();
            //String mediaFile = convertMediaFileName(fo.getRMFileName());

            String URL = mediaFilePath + addSAMIPath();
            
            setVideoTime();

            //string lf = "\n";
            //mh.alert(asxFilePath + lf + copyright + lf + mediaFilePath + lf + URL);

            String startTime = "";
            String duration = "";
            
            if (getDuration() > 0)
            {
                String durationValue = getDuration().ToString().Replace(",", "."); // I hate conversion of decimal numbers ...
                duration = "<DURATION VALUE=\"" + durationValue + "\"/>";
            }
            
            String startTimeValue = getVideoStartTime().ToString().Replace(",", ".");
            startTime = "<STARTTIME VALUE=\"" + startTimeValue + "\"/>";
            
            String content = "<ASX version=\"3.0\">\n   <ENTRY>\n      <TITLE>Telos Video</TITLE>\n      <COPYRIGHT>" + copyright + ", duplication and capturing prohibited</COPYRIGHT>\n      <REF HREF=\"" + URL + "\">\n         "+startTime+"\n         "+duration+"\n      </REF>\n   </ENTRY>\n</ASX>";

            return fo.writeFile(asxFilePath, content.Split('\n').ToList());
            //mh.alert("Trying to write file: \n" + asxFilePath);
            //return true;
        }

        private String addSAMIPath()
        {
            if (fo.getRTAvailable())
                return "?sami=" + fo.getSAMIWebCaptionFilePath();// + fo.getSAMIFileDir() + fo.getSAMICaptionFileName();
            else
                return "";
            
        }
    }
}
